<template>
  <div class="message-box">

    <el-form :model="form" :rules="rules" ref="formRef" label-position="right" label-width="130px">

      <el-form-item label="账号:">
        <span class="name-box" >{{form.account}}</span>
        <el-button type="danger" @click="logout" class="setting_button">
          注销账号
        </el-button>
        <el-button @click="changePassword">
          修改密码
        </el-button>
      </el-form-item>

      <el-form-item label="用户昵称:" prop="username">
        <el-input v-model="form.username" class="name-box" />
      </el-form-item>

      <el-form-item label="绑定邮箱:" prop="email">
        <span  class="name-box">{{form.email}}</span>
        <el-button @click="changeEmail" class="setting_button">
          修改邮箱
        </el-button>
      </el-form-item>

      <el-form-item label="性别:" prop="gender">
        <el-radio-group v-model="form.gender">
          <el-radio label="男">
            男
          </el-radio>
          <el-radio label="女">
            女
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="个人签名:" prop="signature">
        <el-input type="textarea" :rows="5" placeholder="请输入个人签名" v-model="form.signature" maxlength="100"
          show-word-limit resize="none" class="signbox" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">
          更新信息
        </el-button>
        <el-button @click="resetForm">
          取消修改
        </el-button>
      </el-form-item>

    </el-form>

    <!-- 修改密码弹窗 -->
    <el-dialog :model-value="PasswordDialogVisible" @close="resetPasswordForm" :before-close="beforeClose">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="150px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" placeholder="原密码" show-password>
          </el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="新密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="确认新密码" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitPasswordForm">确认修改</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 修改邮箱弹窗 -->
    <el-dialog :model-value="EmailDialogVisible" @close="resetEmailForm" :before-close="beforeClose">

      <el-form :model="emailForm" :rules="emailRules" ref="emailFormRef" label-width="150px">
        <el-form-item label="新邮箱" prop="newEmail">
          <div class="verificationCode-box">
            <el-input v-model="emailForm.newEmail" placeholder="请输入新邮箱" />
            <el-button @click="sendVerificationCode">
              发送验证码
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="验证码" prop="verificationCode">
          <el-input v-model="emailForm.verificationCode" placeholder="请输入验证码" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitEmailForm">
            确认修改
          </el-button>
        </el-form-item>

      </el-form>
    </el-dialog>

  </div>

</template>

<script setup>
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { user_GET_info, user_MODIFY_info} from '@/apis/user_GET_info';

const { proxy } = getCurrentInstance();
const PasswordDialogVisible = ref(false);
const EmailDialogVisible = ref(false);
const passwordFormRef = ref();
const emailFormRef = ref();
const formRef = ref();

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
})

const emailForm = reactive({
  newEmail: '',
  verificationCode: '',
})

const form = reactive({
  account: '',
  email: '',
  username: '',
  gender: '',
  signature: '',
})

const rules = {
  username: [
    { min: 3, max: 10, message: '昵称长度为3-10个字符', trigger: 'blur' },
  ],
  signature: [
    { max: 100, message: '个人签名不能超过100个字符', trigger: ['blur', 'change'] },
  ],
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度为6-16个字符', trigger: ['change', 'blur'] },
    { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/, message: '密码必须包含字母和数字', trigger: ['change', 'blur'] },
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度为6-16个字符', trigger: ['change', 'blur'] },
    { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/, message: '密码必须包含字母和数字', trigger: ['change', 'blur'] },
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, trigger: ['change', 'blur']
    },
  ],
}

const emailRules = {
  newEmail: [
    { required: true, message: '请输入新邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] },
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
  ],
}

const changePassword = () => {
  PasswordDialogVisible.value = true
}

const changeEmail = () => {
  EmailDialogVisible.value = true
}

// 关闭弹窗之前
const beforeClose = () => {
  PasswordDialogVisible.value = false
  EmailDialogVisible.value = false
}

const resetPasswordForm = () => {
  passwordFormRef.value.resetFields()
}

const resetEmailForm = () => {
  emailFormRef.value.resetFields()
}

//修改密码
const submitPasswordForm = async () => {
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      await proxy.$http.post('/pass_change/', {
        pass_old: passwordForm.oldPassword,
        pass_new: passwordForm.newPassword
      }).then((res) => {
        if (res.data.status == "success") {
          ElMessage.success("修改密码成功")
          PasswordDialogVisible.value = false
        } else {
          ElMessage.error(res.data.message)
        }
      }).catch((err) => {
        ElMessage.error('请求失败，请稍后重试')
      })
    } else {
      ElMessage.error('请检查输入内容')
    }
  })
}

//发送修改邮箱的验证码
const sendVerificationCode = async () => {
  await proxy.$http.post('/email_change/', {
    type: 'yzm',
    email: emailForm.newEmail
  }).then((res) => {
    if (res.data.status == "success")
      ElMessage.success("验证码已发送");
    else
      ElMessage.error(res.data.message);
  }).catch((err) => {
    ElMessage.error('请求失败，请稍后重试')
  })
}

//修改邮箱
const submitEmailForm = async () => {
  await emailFormRef.value.validate(async (valid) => {
    if (valid) {
      await proxy.$http.post('/email_change/', {
        type: 'gg',
        email: emailForm.newEmail,
        code: emailForm.verificationCode
      }).then((res) => {
        if (res.data.status == "success") {
          ElMessage.success("修改邮箱成功")
          EmailDialogVisible.value = false
          form.email = emailForm.newEmail
        } else {
          ElMessage.error(res.data.message)
        }
      }).catch((err) => {
        ElMessage.error('请求失败，请稍后重试')
      })
    } else {
      ElMessage.error('请检查输入的验证码')
    }
  })
}

//更新个人信息
const submitForm = async () => {
  await formRef.value.validate(async (valid) => {
    if (valid) {
      // 发送更新请求
      let sex = false;
      if(form.gender == '男')
        sex = true;
      const response = await user_MODIFY_info(proxy, form.username, sex, form.signature);
      ElMessage.success('信息更新成功');
    }
    else
      ElMessage.error('表单校验失败，请检查输入内容');
  })
}

//注销账号
const logout = async () => {
  await proxy.$http.post('/Del/').then((res) => {
    if (res.data.status == "success") {
      localStorage.removeItem('token'); // 移除本地存储的 token
      localStorage.removeItem('account')
      ElMessage.success("注销成功");
      router.push('/'); // 重定向到主页
    } else {
      ElMessage.error(res.data.message)
    }
  }).catch((err) => {
    
  })
}

const resetForm = () => {
  formRef.value.resetFields()
}

// 加载用户信息
const loadUserInfo = async () => {
  try {
    const response = await user_GET_info(proxy);
    form.account = response.data.user_name;
    form.email = response.data.email;
    form.username = response.data.nickname;
    form.gender='女';
    if(response.data.sex == true)
      form.gender='男';
    form.signature = response.data.sig;
  } catch (error) {
    ElMessage.error('加载用户信息失败')
  }
}

onMounted(loadUserInfo);

</script>

<style scoped>
.message-box {
  background-color: white;
  border-radius: 10px;
  margin-top: 2%;
  padding-top: 10px;
  width: 100%;
  height: 70%;
  border: 1px solid rgba(255, 255, 255, 0.6);
  box-shadow: 2px 1px 19px rgba(0, 0, 0, 0.1);
}

.message-box .el-form-item {
  margin-bottom: 20px;
}

.message-box span {
  width: 180px;
}

.message-box .el-form {
  margin-left: 3%;
  margin-top: 3%;
}

.name-box {
  width: 30%;
}

.signbox {
  width: 55%;
}

.verificationCode-box {
  width: 100%;
  display: flex;
  align-items: center;
  gap: 10px;
}

.el-dialog .el-form {
  width: 50%;
}

.setting_button {
  margin-left: 2%;
}
</style>